package design.action.memento;

import cn.hutool.core.collection.CollUtil;
import lombok.ToString;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author zxs
 * @since 2020/05/29
 */
@ToString
public class Caretaker {
    private final ConcurrentMap<String, BoundedQueue<Memento>> history = new ConcurrentHashMap<>();

    private final int capacity;

    public Caretaker(int capacity){
        this.capacity = capacity;
    }

    public void saveMemento(String type,Memento memento){
        BoundedQueue<Memento> queue = history.computeIfAbsent(type,(key)->new BoundedQueue<>(capacity));
        queue.offer(memento);
    }

    public Memento getMemento(String type){
        BoundedQueue<Memento> queue = history.get(type);
        return CollUtil.isEmpty(queue)?null : queue.getLast();
    }
}
